export default class NewGroupText {
  constructor(options) {
    this.canvas = options.canvas

    let g = new fabric.Group()

    let rect = new fabric.Rect({
      fill: '#efefef'
    })

    g.addWithUpdate(rect)
    let text = new fabric.Text('helloworld', {
      fontSize: 30,
      lineHeight: 1,
      left: 0,
      top: 0
    })
    g.addWithUpdate(text)

    rect.set({
      width: g.width,
      height: g.height
    })

    g.controls = {}
    g.controls.rb = new fabric.Control({
      x: 0.5,
      y: 0.5,
      mouseDownHandler: (e, transform, x, y) => this.down(e, transform, x, y),
      mouseUpHandler: (e, transform, x, y) => this.up(e, transform, x, y),
      actionHandler: (e, transform, x, y) => this.action(e, transform, x, y)
    })

    this.g = g
    this.rect = rect
    this.text = text
    this.canvas.add(g)

    g.on('modified', () => {
      //this.rect.set({
      //width: g.width,
      //height: g.height,
      //left: -g.width / 2,
      //top: -g.height / 2
      //})
    })
    g.set({
      selectionBackgroundColor: '#efefef',
      backgroundColor: '#efefef'
    })
    g.addWithUpdate()
  }
  action(e, transform, x, y) {
    let dx = x - this.ox
    let dy = y - this.oy

    let tw = this.text.width
    let th = this.text.height

    let w = this.ow + dx
    let h = this.oh + dy

    w = w < tw ? tw : w
    h = h < th ? th : h

    w = w > 2 * tw ? 2 * tw : w
    h = h > 2 * th ? 2 * th : h

    this.g.set({
      width: w,
      height: h
    })

    this.canvas.renderAll()
    this.g.fire('modified')
  }
  down(e, transform, x, y) {
    this.isDown = true
    this.ox = x
    this.oy = y
    this.ow = this.g.width
    this.oh = this.g.height
  }
  up(e, transform, x, y) {
    this.isDown = false
    let w = this.g.width
    let h = this.g.height
    this.rect.set({
      width: w,
      height: h,
      left: -w / 2,
      top: -h / 2
    })
  }
}
